// 工具函数

// 格式化时间
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

// 格式化日期
const formatDate = date => {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = d.getMonth() + 1
  const day = d.getDate()

  return `${year}-${formatNumber(month)}-${formatNumber(day)}`
}

// 格式化数字
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 防抖函数
const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 显示成功提示
const showSuccess = (title = '操作成功') => {
  wx.showToast({
    title,
    icon: 'success',
    duration: 2000
  })
}

// 显示错误提示
const showError = (title = '操作失败') => {
  wx.showToast({
    title,
    icon: 'none',
    duration: 2000
  })
}

// 显示加载提示
const showLoading = (title = '加载中...') => {
  wx.showLoading({
    title,
    mask: true
  })
}

// 隐藏加载提示
const hideLoading = () => {
  wx.hideLoading()
}

// 确认对话框
const showConfirm = (content, title = '提示') => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title,
      content,
      success: (res) => {
        if (res.confirm) {
          resolve(true)
        } else {
          reject(false)
        }
      }
    })
  })
}

// 获取图片完整路径
const getImageUrl = (path) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  const app = getApp()
  return app.globalData.baseUrl + path
}

// 检查登录状态
const checkLogin = () => {
  const app = getApp()
  if (!app.globalData.isLogin) {
    // 直接跳转到游客提示页面
    wx.navigateTo({
      url: '/pages/guest-prompt/guest-prompt'
    })
    return false
  }
  return true
}

// 验证token是否有效
const validateToken = () => {
  const app = getApp()

  // 检查全局状态
  if (!app.globalData.isLogin || !app.globalData.userInfo || !app.globalData.userInfo.token) {
    return false
  }

  // 检查本地存储
  const userInfo = wx.getStorageSync('userInfo')
  if (!userInfo || !userInfo.token) {
    return false
  }

  // 检查token是否一致
  if (app.globalData.userInfo.token !== userInfo.token) {
    console.warn('全局状态和本地存储的token不一致，重新同步')
    app.refreshLoginStatus()
    return app.globalData.isLogin
  }

  return true
}

// 检查登录状态（用于tabBar页面）
const checkLoginForTabBar = () => {
  const app = getApp()

  // 先验证token
  if (!validateToken()) {
    console.log('Token验证失败，跳转到游客提示页面')
    // 对于tabBar页面，跳转到游客提示页面
    wx.navigateTo({
      url: '/pages/guest-prompt/guest-prompt'
    })
    return false
  }

  return true
}

// 页面跳转
const navigateTo = (url) => {
  wx.navigateTo({
    url
  })
}

// 页面重定向
const redirectTo = (url) => {
  wx.redirectTo({
    url
  })
}

// 返回上一页
const navigateBack = (delta = 1) => {
  wx.navigateBack({
    delta
  })
}

// 获取当前页面路径
const getCurrentPagePath = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage.route
}

module.exports = {
  formatTime,
  formatDate,
  formatNumber,
  debounce,
  throttle,
  showSuccess,
  showError,
  showLoading,
  hideLoading,
  showConfirm,
  getImageUrl,
  checkLogin,
  checkLoginForTabBar,
  validateToken,
  navigateTo,
  redirectTo,
  navigateBack,
  getCurrentPagePath
}
